var vm = new Vue({
    el: '#app',
    data: {
        tableData: [],//表格当前页数据
        pagesize: 20,//默认每页数据量
        facilitator: {}, //当前选择行数据
        currentPage: 1,//当前页码
        start: 1, //查询的页码
        totalCount: '',//默认数据总数
        multipleSelection: [],//多选数组
        dialogFormVisible:false,//编辑框
        q:{//搜索条件
            param:'',
        },
        idCardImgs:[],//身份证正反面url
        showList:true,
        editView:false,
        checkView:false,
        title:'',
        areaCascader: [], //省市区回显
        options:[],//省市区data
        shops:[],//省市区下的商家
        shopIdsList:[],
        areaList:[],//审核页面省市区信息
        shopList:'',//审核页面商家信息
        auditVoList:[],//审核页面待审核信息
        qa:{
            sellerName:'',
            sellerMobile:'',
            sellerQq:'',
        },
        facilitatorId:'',//服务商id
    },
    created () {
        Vue.nextTick(()=>{
            //载入数据
            vm.loadData(vm.currentPage, vm.pagesize);
        });
    },
    mounted: function(){
        this.filesUploadInit();
    },
    methods: {
        //从后台获取数据
        loadData: function (page, limit) {
            vm.q.page=vm.currentPage
            vm.q.limit=vm.pagesize
            $.ajax({
                type: "POST",
                url: baseURL + "facilitator/facilitator/list",
                contentType: "application/json",
                data: JSON.stringify(vm.q),
                success: function(r){
                    if(r.code === 0){
                        vm.tableData = r.page.list
                        vm.totalCount = r.page.totalCount
                        var options = JSON.parse(r.regions);
                        vm.options = options;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        //多选响应
        handleSelectionChange: function(val) {
            vm.multipleSelection = val;
            console.log(vm.multipleSelection)
        },
        //点击行响应
        handleclick: function(row, event, column){
            vm.facilitator = JSON.parse(JSON.stringify(row));//深克隆
        },
        //编辑
        handleEdit: function(index, row) {
            vm.getInfo(row.teamId)
            vm.title = "编辑";
            document.getElementById("shop").innerHTML =''
            document.getElementById("shopIds").innerHTML =''
            document.getElementById("phoneTextarea").innerHTML =''
            vm.shopIdsList=[[]]
            vm.showList = false;
            vm.editView = true;
        },
        //删除
        handleDelete: function() {
            $.ajax({
                type: "POST",
                url: baseURL + "facilitator/facilitator/delete",
                contentType: "application/json",
                data: JSON.stringify(vm.multipleSelection),
                success: function(r){
                    if(r.code === 0){
                        alert('删除成功')
                        vm.loadData(vm.currentPage, vm.pagesize);//刷新后页面在当前页
                        //vm.loadData(vm.currentPage=1, vm.pagesize);刷新后页面回到首页
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        //搜索
        search: function(){
            vm.loadData(vm.start, vm.pagesize);
        },
        //重置
        rest() {
            vm.q.param=''
            vm.loadData(vm.currentPage, vm.pagesize);
        },
        add() {
            vm.title = "新增";
            vm.idCardImgs=[]
            vm.shopIdsList=[[]]
            vm.facilitator = {};
            vm.showList = false;
            vm.editView = true;
        },
        getInfo(teamId) {
            $.get(baseURL + "facilitator/facilitator/info/"+teamId, function(r){
                vm.facilitator = r.facilitator;
                if (vm.facilitator.idCardUrls) {
                    vm.idCardImgs=vm.facilitator.idCardUrls.split(',')
                    Vue.nextTick(function () {
                        $('.showview').viewer();
                    })
                }
            });
        },
        //每页显示数据量变更
        handleSizeChange: function(val) {
            vm.pagesize = val;
            vm.loadData(vm.currentPage, vm.pagesize);
        },
        //页码变更
        handleCurrentChange: function(val) {
            vm.currentPage = val;
            vm.loadData(vm.currentPage, vm.pagesize);
        },
        //省市区级联
        handleItemChange: function(val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length-1];
            var lableObj = getCascaderObj(val, vm.options);
            var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
            $.get(baseURL + "facilitator/facilitator/getShops/"+lable, function(r){
                if(r.code === 0){
                    vm.shops=r.shops
                }
            });
        },
        audit: function (formName) {
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    if (!(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(vm.facilitator.mobile))) {
                        alert("手机号码格式不正确");
                        return false;
                    }
                    if (!vm.idCardImgs[0]||!vm.idCardImgs[1]){
                        alert('请上传身份证正反面')
                        return
                    }
                    if (!vm.facilitator.agreementUrl||!vm.facilitator.businessUrl){
                        alert('请上传合同和营业执照')
                        return
                    }
                    //遍历vm.shopIdsList获取sellerIds
                    var sellerIds=''
                    vm.shopIdsList.forEach(v=>{
                        if (v.length>0){
                            v.forEach(o=>{
                                sellerIds+=','+o
                            })
                        }
                    })

                    //获取导入的sellerIds
                    var sellerIdsR=$('#shopIds').val().split(',')
                    //导入的sellerIds去重
                    let set = new Set()
                    sellerIdsR.map(x => set.add(x));
                    //合并左右两边的sellerIds
                    if (set.size>0){
                        sellerIds+=','+[...set].join(',')
                    }
                    if (sellerIds.startsWith(',')) {
                        sellerIds=sellerIds.substring(1)
                    }

                    var phoneTextarea=$('#phoneTextarea').val().split(',')
                    set.clear()
                    phoneTextarea.map(x => set.add(x));
                    var phones=[...set].join(',')

                    vm.facilitator.idCardUrls=vm.idCardImgs.join(',')
                    vm.facilitator.sellerIds=sellerIds
                    vm.facilitator.phones=phones

                    var url = vm.facilitator.teamId == null ? "facilitator/facilitator/save" : "facilitator/facilitator/update";
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(vm.facilitator),
                        success: function (r) {
                            if (r.code === 0) {
                                vm.$alert('操作成功!', '提示', {
                                    confirmButtonText: '确定',
                                    callback: function (action) {
                                        vm.loadData(vm.currentPage = 1, vm.pagesize);//刷新后回到首页
                                        vm.showList=true
                                        vm.editView = false;
                                    }
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });

        },
        addlist() {
            vm.shopIdsList.push([])
        },
        dellist (index) {
            if (vm.shopIdsList.length > 1) {
                vm.shopIdsList.splice(index, 1);
            }
        },
        /* 初始化oss上传 */
        filesUploadInit: function () {
            $.files_up_oss({
                id: ["upload1", 'upload2', 'upload3','upload4'],// 按钮id
                url: "/sys/oss/getSignature",
                dir: "seller/sellerimage/",
                file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
                size: "100mb",//mb
                // view_url: "https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/"
                view_url: window.parent.vm.ossHost
            }, function (index_number, json) {
                if (json.Status == 'OK'){
                    if (index_number == 0) {
                        console.log(json.filename)
                        Vue.set(vm.idCardImgs,0, json.filename)
                    }else if (index_number == 1) {
                        Vue.set(vm.idCardImgs,1, json.filename)
                    }else if (index_number == 2) {
                        vm.facilitator.agreementUrl=json.filename
                    }else if (index_number == 3) {
                        vm.facilitator.businessUrl=json.filename
                    }
                }else {
                    alert("OSS上传失败，请联系后台管理员！");
                }
            });
        },
        delFlagFormatter: function (val) {
            if (val.delFlag == 0) {
                return '正常'
            }
            else if (val.delFlag == 1) {
                return '冻结'
            }
            else {
                return ''
            }
        },
        //跳转到审核页面
        handleCheck(index, row) {
            vm.facilitatorId=row.userId
            //查询该服务商下商户的省市区及商户及待审核列表信息
            $.get(baseURL + "facilitator/facilitator/chenckShop/"+row.userId, function(r){
                if(r.code === 0){
                    vm.areaList=r.areaList
                    vm.shopList=r.shopList
                    vm.auditVoList=r.auditVoList
                }
            });

            vm.showList=false
            vm.checkView=true
        },
        refuse(index, row,flag) {
            //flag=1通过 flag=0拒绝
            if (flag == 1) {
                $.get(baseURL + "facilitator/facilitator/refuse/"+row.id+"/"+flag, function(r){
                    if(r.code === 0){
                        alert('操作成功')
                        //查询该服务商下商户的省市区及商户及待审核列表信息
                        $.get(baseURL + "facilitator/facilitator/chenckShop/"+row.parentUserId, function(r){
                            if(r.code === 0){
                                vm.areaList=r.areaList
                                vm.shopList=r.shopList
                                vm.auditVoList=r.auditVoList
                            }
                        });
                    }
                });
            }
        },
        closeCheckView() {
            vm.loadData(vm.currentPage, vm.pagesize);
            vm.showList=true
            vm.checkView=false
        },
        searchQ() {
            vm.qa.userId =vm.facilitatorId
            $.ajax({
                type: "POST",
                url: baseURL + "facilitator/facilitator/searchQ",
                contentType: "application/json",
                data: JSON.stringify(vm.qa),
                success: function(r){
                    if(r.code === 0){
                        vm.auditVoList=r.auditVoList
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        restQ() {
            vm.qa.userId =vm.facilitatorId
            vm.qa.sellerName =''
            vm.qa.sellerMobile =''
            vm.qa.sellerQq =''

            $.ajax({
                type: "POST",
                url: baseURL + "facilitator/facilitator/searchQ",
                contentType: "application/json",
                data: JSON.stringify(vm.qa),
                success: function(r){
                    if(r.code === 0){
                        vm.auditVoList=r.auditVoList
                    }else{
                        alert(r.msg);
                    }
                }
            });

        }
    }
});

function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children; return label;
            }
        }
        return null;
    });
}

var wb; //读取完成的数据
var worksheet = [];
var text = [];
var rABS = false; //是否将文件读取为二进制字符串

function importExcel(obj) { //导入
    if (!obj.files) {
        return;
    }
    const IMPORTFILE_MAXSIZE = 1 * 2048; //这里可以自定义控制导入文件大小
    var suffix = obj.files[0].name.split(".")[1]
    if (suffix != 'xls' && suffix != 'xlsx') {
        alert('导入的文件格式不正确!')
        return
    }
    if (obj.files[0].size / 1024 > IMPORTFILE_MAXSIZE) {
        alert('导入的表格文件不能大于2M')
        return
    }
    var f = obj.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        if (rABS) {
            wb = XLSX.read(btoa(fixdata(data)), { //手动转化
                type: 'base64'
            });
        } else {
            wb = XLSX.read(data, {
                type: 'binary'
            });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        worksheet = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
        var u = eval('(' + worksheet + ')');

        if (obj.files[0].name.indexOf('商户信息导入表')!=-1){
            for (var i = 0; i < u.length; i++) {
                if(/^[0-9]*$/.test(u[i].商户id))
                    text.push(u[i].商户id+u[i].商户名称);
            }
            document.getElementById("shop").innerHTML = text
            text=[]
            for (var i = 0; i < u.length; i++) {
                if(/^[0-9]*$/.test(u[i].商户id))
                    text.push(u[i].商户id);
            }
            document.getElementById("shopIds").innerHTML = text

        }else if (obj.files[0].name.indexOf('代理商信息导入表')!=-1){
            text=[]
            //获取表格中表头为'手机号码'的那列存入text中
            for (var i = 0; i < u.length; i++) {
                if(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(u[i].手机号码))
                    text.push(u[i].手机号码);
            }
            document.getElementById("phoneTextarea").innerHTML = text
        }
        text=[]
    };
    if (rABS) {
        reader.readAsArrayBuffer(f);
    } else {
        reader.readAsBinaryString(f);
    }
}

//下载Excel模板
var $eleBtn1 = $("#btn1");
var $eleBtn2 = $("#btn2");
$eleBtn1.click(function(){
    var $eleForm = $("<form method='get'></form>");
    $eleForm.attr("action","https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/erp/file/%E4%BB%A3%E7%90%86%E5%95%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E8%A1%A8.xlsx");
    $(document.body).append($eleForm);
    //提交表单，实现下载
    $eleForm.submit();
});
$eleBtn2.click(function(){
    var $eleForm = $("<form method='get'></form>");
    $eleForm.attr("action","https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/erp/file/%E5%95%86%E6%88%B7%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E8%A1%A8.xlsx");
    $(document.body).append($eleForm);
    //提交表单，实现下载
    $eleForm.submit();
});